package scau.gsmg.misp.service.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import scau.gsmg.misp.dao.IReturnGoodsDAO;
import scau.gsmg.misp.dao.impl.CheckoutDAO;
import scau.gsmg.misp.service.IReturnGoodsService;
import scau.gsmg.misp.vo.SaleOrder;
import scau.gsmg.misp.vo.SaleReturn;
import scau.gsmg.misp.vo.User;

/**
 * @Title 退货
 * @Group gaoshenmegui
 * @author ZCL
 * @date 2015年5月9日
 */
@Service
public class ReturnGoodsService implements IReturnGoodsService {
	
	private IReturnGoodsDAO returnGoodsDAO;
	private static final Logger logger = Logger.getLogger(CheckoutDAO.class);
	
	public IReturnGoodsDAO getReturnGoodsDAO() {
		return returnGoodsDAO;
	}
	@Resource
	public void setReturnGoodsDAO(IReturnGoodsDAO returnGoodsDAO) {
		this.returnGoodsDAO = returnGoodsDAO;
	}
	/**
	 * 通过小票流水号搜索支付单，返回支付单的商品
	 */
	@Override
	public List searchPayment(String paymentId) throws Exception {
		// TODO Auto-generated method stub
		String saleOrderId = returnGoodsDAO.gainSaleOrderId(paymentId);//得到销售单号
		List saleOrder = returnGoodsDAO.gainSaleOrder(saleOrderId);//获取销售单
		return returnGoodsDAO.gainGoods(saleOrderId);
	}
	
	/**
	 * 得到销售单信息
	 */
	@Override
	public List gainSaleOrder(String paymentId) throws Exception {
		// TODO Auto-generated method stub
		return returnGoodsDAO.gainSaleOrder(paymentId);
	}
	
	/**
	 * 获取退货单号
	 */
	@Override
	public String gainReturnId() throws Exception {
		// TODO Auto-generated method stub
		String strOrder  = returnGoodsDAO.lastReturnRecord();
		String orderDate = "";// 日期
		String orderOrder = "";// 顺序
		String orderId = "";// 单号
		Date nowDate = new Date();// 当前时间
		String formatNowDate = new SimpleDateFormat("yyyyMMdd").format(nowDate);
		if (strOrder != null) {
			String date = strOrder.substring(3, 11);// 获取日期部分
			String order = strOrder.substring(12, 16);// 获取排序部分
			// 判断是不是今天的第一单
			if (formatNowDate.equals(date)) {
				orderDate = formatNowDate;
				int orderOrderInt = Integer.parseInt(order) + 1;
				orderOrder = String.format("%4d", orderOrderInt).replace(" ","0");
			} else {
				orderDate = formatNowDate;
				orderOrder = "0001";
			}
			orderId = orderDate + "-" + orderOrder;// 得到订单号
		} else {
			orderId = formatNowDate + "-" + "0001";
		}
		return "sr" + "-" + orderId;
	}
	
	/**
	 * 退货
	 */
	@Override
	public boolean returnGoods(String rowObj,String paymentId, int userId,
			String returnId, double total, int amount, int integral,int customerId)
			throws Exception {
		// TODO Auto-generated method stub
		String saleOrderId = returnGoodsDAO.gainSaleOrderId(paymentId);//得到销售单号
		int saleId = returnGoodsDAO.gainSaleId(paymentId);//得到销售单号
		
//		在退货表生成记录
		Date saleDate = new Date();
		String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(saleDate);
		Timestamp time = Timestamp.valueOf(nowTime);
		SaleOrder saleOrder =  returnGoodsDAO.gainSaleOrderObj(saleOrderId);//得到销售单对象
		User user = returnGoodsDAO.gainUser(userId);
		SaleReturn saleReturn = returnGoodsDAO.createSaleReturn(returnId, saleOrder, total, amount, user, time);
		
//		在退货商品表生成记录
		boolean isCreate = returnGoodsDAO.writeReturnGoods(rowObj, saleReturn, saleOrderId);
		if(isCreate){
//			修改原销售单信息（更新总数量，总金额，应收款）
			JSONArray jsonArray = JSONArray.fromObject(rowObj);// 把从前台得到的json字符串转换成json数组
			double totalPrice = 0;
			for (int i = 0; i < jsonArray.size(); i++) {
				totalPrice += jsonArray.getJSONObject(i).getDouble("totalprice");
			}
			boolean isUpdateSaleOrder = returnGoodsDAO.updateSaleOrder(amount, totalPrice, total, saleId);
			
//			修改原支付单信息（更新找款）
			boolean isUpdatePayment = returnGoodsDAO.updatePayment(total,saleId);
			
//			修改原销售商品表信息（更新数量，更新金额）
			boolean isUpdateSaleOrderItems = returnGoodsDAO.updateSaleOrderItems(rowObj, saleId);

			if(isUpdateSaleOrder&&isUpdatePayment&&isUpdateSaleOrderItems){
//				扣除会员积分
				returnGoodsDAO.updateIntegral(customerId,integral);
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}

		
	}
	

}
